<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车辆品牌" prop="vehicleName">
        <el-input
          v-model="queryParams.vehicleName"
          placeholder="请输入车辆品牌"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌号" prop="licenseNo">
        <el-input
          v-model="queryParams.licenseNo"
          placeholder="请输入车牌号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属商户" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入所属商户"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经营范围" prop="routeCode">
        <el-input
          v-model="queryParams.routeCode"
          placeholder="请输入经营范围"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="自编号" prop="selfNo">
        <el-input
          v-model="queryParams.selfNo"
          placeholder="请输入自编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="锁标识" prop="lockFlag">
        <el-input
          v-model="queryParams.lockFlag"
          placeholder="请输入锁标识"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['vehicle:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['vehicle:info:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['vehicle:info:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="danger"-->
<!--            plain-->
<!--            icon="Delete"-->
<!--            :disabled="multiple"-->
<!--            @click="handleAddress"-->
<!--            v-hasPermi="['vehicle:info:remove']"-->
<!--        >车辆位置</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['vehicle:info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车辆编码" align="center" prop="vehicleCode" />
      <el-table-column label="车辆品牌" align="center" prop="vehicleName" />
      <el-table-column label="车牌号" align="center" prop="licenseNo" />
      <el-table-column label="车牌颜色" align="center" prop="licenseColor" />
      <el-table-column label="所属商户" align="center" prop="deptName" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="chelaing_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="营运编号" align="center" prop="certificateNo" />
      <el-table-column label="营运有效期" align="center" prop="certificateExpiryDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.certificateExpiryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="经营范围" align="center" prop="routeCode" />
      <el-table-column label="办卡日期" align="center" prop="makeCardTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.makeCardTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="办卡人" align="center" prop="makeCardUser" />
      <el-table-column label="自编号" align="center" prop="selfNo" />
      <el-table-column label="锁标识" align="center" prop="lockFlag">
        <template #default="scope">
          <dict-tag :options="sys_notice_status" :value="scope.row.lockFlag" />
        </template>
      </el-table-column>
      <el-table-column label="出厂日期" align="center" prop="productionDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="产品名称" align="center" prop="productionName" />-->
<!--      <el-table-column label="有效期" align="center" prop="workExpiryDate" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.workExpiryDate, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="工作状态" align="center" prop="workStatus" >
        <template #default="scope">
          <dict-tag :options="work_status" :value="scope.row.workStatus" />
        </template>
      </el-table-column>
      <el-table-column label="电量" align="center" prop="battery" />
      <el-table-column label="使用用户" align="center" prop="workUser" />
      <el-table-column label="地址" align="center" prop="address" />
<!--      <el-table-column label="部门ID" align="center" prop="deptId" />-->
<!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['vehicle:info:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['vehicle:info:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车辆信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="infoRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车辆品牌" prop="vehicleName">
          <el-input v-model="form.vehicleName" placeholder="请输入车辆品牌" />
        </el-form-item>
        <el-form-item label="车牌号" prop="licenseNo">
          <el-input v-model="form.licenseNo" placeholder="请输入车牌号" />
        </el-form-item>
<!--        <el-form-item label="车辆等级" prop="vehicleLevel">-->
<!--          <el-input v-model="form.vehicleLevel" placeholder="请输入车辆等级" />-->
<!--        </el-form-item>-->
        <el-form-item label="车牌颜色" prop="licenseColor">
          <el-input v-model="form.licenseColor" placeholder="请输入车牌颜色" />
        </el-form-item>
        <el-form-item label="所属商户" prop="deptName">
          <el-input v-model="form.deptName" placeholder="默认商户自己" />
        </el-form-item>
        <el-form-item label="营运编号" prop="certificateNo">
          <el-input v-model="form.certificateNo" placeholder="请输入营运编号" />
        </el-form-item>
        <el-form-item label="营运有效期" prop="certificateExpiryDate">
          <el-date-picker clearable
            v-model="form.certificateExpiryDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择营运有效期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="经营范围" prop="routeCode">
          <el-input v-model="form.routeCode" placeholder="请输入经营范围" />
        </el-form-item>
<!--        <el-form-item label="办卡日期" prop="makeCardTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.makeCardTime"-->
<!--            type="date"-->
<!--            value-format="YYYY-MM-DD"-->
<!--            placeholder="请选择办卡日期">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="办卡人" prop="makeCardUser">-->
<!--          <el-input v-model="form.makeCardUser" placeholder="请输入办卡人" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="自编号" prop="selfNo">-->
<!--          <el-input v-model="form.selfNo" placeholder="请输入自编号" />-->
<!--        </el-form-item>-->
        <el-form-item label="锁标识" prop="lockFlag">
          <el-select v-model="form.lockFlag" placeholder="请选择">
            <el-option
                v-for="dict in sys_notice_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出厂日期" prop="productionDate">
          <el-date-picker clearable
            v-model="form.productionDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择出厂日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="工作状态" align="center" prop="workStatus" >
          <el-select v-model="form.workStatus" placeholder="请选择">
            <el-option
                v-for="dict in work_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用用户" prop="workUser">
          <el-input v-model="form.workUser" placeholder="请输入使用用户" />
        </el-form-item>
        <el-form-item label="当前电量" prop="battery">
          <el-input v-model="form.battery" placeholder="请输入当前电量" />
        </el-form-item>
        <el-form-item label="地址" prop="res">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="部门ID" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入部门ID" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改车辆信息对话框 -->
    <el-dialog v-model="openMap"  @opened="initMap" v-show="isShow">
      <div class="mask">
        <div id="box">
          <div class="title">
            选择位置
          </div>
<!--          <div class="search">-->
<!--            <el-input v-model="searchInput" placeholder="搜索" id="search_input"></el-input>-->
<!--            <el-button type="primary">搜索</el-button>-->
<!--          </div>-->
          <div id="container"></div>
          <div class="sure">
            <el-button type="primary" @click="sureFn">确认</el-button>
            <el-button @click="cancelFn">取消</el-button>
          </div>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script setup name="Info">
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/vehicle/info";
import {onMounted, ref, defineProps, defineEmits} from "vue"
import AMapLoader from '@amap/amap-jsapi-loader'


const emits = defineEmits(['back'])

let map = null;
let searchInput = ref("")
// 存储标点位置
let positionArr = ref([113.392517,22.517024])
// 存储地址
let addressValue = ref("")
// 使用ref来存储Marker实例
let marker = ref(null)
let lngLatLng = ref(null)
let lngLatLat = ref(null)
let isShow = ref(false);

const { proxy } = getCurrentInstance();
const { sys_notice_status, chelaing_status, work_status } = proxy.useDict("sys_notice_status", "chelaing_status", "work_status");
const infoList = ref([]);
const open = ref(false);
const openMap = ref({});
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const sureFn = ref(undefined);
const cancelFn = ref(undefined);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    vehicleName: null,
    licenseNo: null,
    vehicleType: null,
    motorType: null,
    vehicleLevel: null,
    licenseColor: null,
    deptName: null,
    status: null,
    certificateNo: null,
    certificateExpiryDate: null,
    routeCode: null,
    makeCardTime: null,
    makeCardUser: null,
    selfNo: null,
    lockFlag: null,
    productionDate: null,
    productionName: null,
    workExpiryDate: null,
    workStatus: null,
    workUser: null,
    res: null,
    deptId: null,
  },
  rules: {
    licenseNo: [
      { required: true, message: "车牌号不能为空", trigger: "blur" }
    ],
    vehicleType: [
      { required: true, message: "车型不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "状态(0启用，1禁用）不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);


function initMap(){
// 初始化配置地图
  window._AMapSecurityConfig = {
    securityJsCode: "11fa46171b5a476ff40581ce7737421d",
  };
  AMapLoader.load({
    key: "7f8922a33480e520cc450d7ffa3efb8e", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.PlaceSearch","AMap.AutoComplete","AMap.Marker","AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
  // 异步加载插件
  .then((AMap) => {
    map = new AMap.Map("container", {
      // 设置地图容器id
      viewMode: "2D", // 地图模式
      zoom: 11, // 初始化地图级别
      center: [113.392517,22.517024], // 初始化地图中心点位置
    });

    // 地图点击事件
    map.on('click',(e)=>{
      console.log(e);
      lngLatLng.value = e.lnglat.lng;
      lngLatLat.value = e.lnglat.lat;
      console.log(lngLatLng.value, lngLatLat.value);
      positionArr.value = [lngLatLng.value, lngLatLat.value]
      addressValue.value = ""
      if (marker.value) {
        marker.value.setPosition([lngLatLng.value, lngLatLat.value]);  // 更新Marker位置
      }
    })

    let auto = new AMap.AutoComplete({
      city:"中山市", // 限定城市，默认全国
      input:"search_input",
    })
    let placeSearch = new AMap.PlaceSearch({
      city:"中山市",
      map:map
    });
    auto.on("select",(e)=>{
      placeSearch.search(e.poi.name)
      console.log(e.poi);
      positionArr.value = [e.poi.location.lng,e.poi.location.lat]
      addressValue.value = e.poi.address
      if (marker.value) {
        marker.value.setPosition([e.poi.location.lng,e.poi.location.lat]);  // 更新Marker位置
      }
    })
    // 标点位置
    marker.value = new AMap.Marker({
      position: [113.392517,22.517024], //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
      map: map, // 当操作完成时，应该将结果展示在哪个地图上
    })
    map.add(marker)


    sureFn.value = ()=>{
      isShow.value = false
      emits('back',isShow.value)
      emits('returnData', {
        positionArr:positionArr.value,
        addressValue:addressValue.value
      })
    }

    cancelFn.value = ()=>{
      isShow.value = false
      emits('back',isShow.value)
    }
  })
  .catch((e) => {
    console.log(e);
  });
}

function handleAddress(){
  isShow.value = true;
}

/** 查询车辆信息列表 */
function getList() {
  loading.value = true;
  listInfo(queryParams.value).then(response => {
    infoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    vehicleCode: null,
    vehicleName: null,
    licenseNo: null,
    vehicleType: null,
    motorType: null,
    vehicleLevel: null,
    licenseColor: null,
    deptName: null,
    status: null,
    certificateNo: null,
    certificateExpiryDate: null,
    routeCode: null,
    makeCardTime: null,
    makeCardUser: null,
    selfNo: null,
    lockFlag: null,
    productionDate: null,
    productionName: null,
    workExpiryDate: null,
    workStatus: null,
    workUser: null,
    res: null,
    deptId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("infoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.vehicleCode);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加车辆信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _vehicleCode = row.vehicleCode || ids.value
  getInfo(_vehicleCode).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改车辆信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["infoRef"].validate(valid => {
    if (valid) {
      if (form.value.vehicleCode != null) {
        updateInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _vehicleCodes = row.vehicleCode || ids.value;
  proxy.$modal.confirm('是否确认删除车辆信息编号为"' + _vehicleCodes + '"的数据项？').then(function() {
    return delInfo(_vehicleCodes);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('vehicle/info/export', {
    ...queryParams.value
  }, `info_${new Date().getTime()}.xlsx`)
}

getList();
</script>
<style scoped>
.mask {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  background-color: rgba(0,0,0,.6);
}

#container {
  border-radius: 10px;
  padding:0;
  margin: 0;
  width: 100%;
  height: 100%;
}

.title {
  width: 100%;
  text-align: left;
  margin-bottom: 20px;
}

.search {
  width: 100%;
  height: 30px;
  display: flex;
  margin-bottom: 20px;
}

.search .el-input {
  width: 100%;
  height: 30px;
  border-radius: 5px;
}

.search :deep(.el-input__wrapper) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}
.search .el-button {
  height: 100%;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-left: none;
}

#box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 50%;
  height: 80%;
  margin: 0 auto;
  background-color: #ffffff;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.5);
  padding: 1.5vw;
}

.sure {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 20px;
  width: 100%;
}
</style>